﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Ersur.DevTeam;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using Extensions;

namespace Ersur
{
    public partial class Orders : XForm
    {
        public Orders()
        {
            InitializeComponent();
        }

        private void Orders_Load(object sender, EventArgs e)
        {
            BarcodeRead += Orders_BarcodeRead;
              
            gvOrder.Init(Data.bsOrder);
            gvOrderLines.Init(Data.bsOrderLines);

            gvOrder.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gvOrderLines.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
              
            RepositoryItemMemoExEdit ri = new RepositoryItemMemoExEdit();
            ri.ShowIcon = false;           
            gvOrder.Columns["Address"].ColumnEdit = ri;
            gvOrder.Columns["PrivateNotes"].ColumnEdit = ri;
            gvOrder.Columns["Notes"].ColumnEdit = ri;
            gvOrderLines.Columns["Notes"].ColumnEdit = ri;

            gvOrder.MakeColumnInvisible("PrivateNotes");

            gvOrder.AddSummary();
            gvOrder.MakeColumnsReadOnly("OrderId", "SyncDate", "EditDate", "eMailDate");

            gvOrderLines.MakeColumnInvisible("OrderId", "OrderLinesId");
            gvOrderLines.MakeColumnsReadOnly("ProductId");            
            gvOrderLines.AddSummary();
            
            int visibleIndex = gvOrderLines.Columns["ProductId"].VisibleIndex + 1;

            foreach (string col in Data.ProductDetails)
            {
                GridColumn gcTemp = gvOrderLines.Columns[col];
                gcTemp.OptionsColumn.AllowEdit = false;
                gcTemp.VisibleIndex = visibleIndex++;
                gcTemp.FilterMode = ColumnFilterMode.DisplayText;
            }

            gvOrder.MoveLast();
            GridManager gmOrder = new GridManager(gvOrder);

            gmOrder.GridMenu.AddMenu("Add product", AddProductManual_Click);
            gmOrder.GridMenu.AddMenu("Print order(s)", PrintOrder_Click,true);
            gmOrder.GridMenu.AddMenu("Print order's article(s)", PrintOrderArticles_Click);
            gmOrder.GridMenu.AddMenu("Sync row(s)", Sync_Click, true);
            gmOrder.GridMenu.AddMenu("Send e-mail(s)", SendMail_Click);
            gmOrder.GridMenu.AddMenu("Mark row(s) as sent", MarkAsSent_Click, true);
              
            GridColumn gc = new GridColumn();
            gc.Name = "Remove";
            gc.Caption = "Remove";
            gc.VisibleIndex = 900;
            gvOrderLines.Columns.Add(gc);

           

            gvOrder.RowStyle += gvOrder_RowStyle;
            gvOrder.RowCellStyle += gvOrder_RowCellStyle;
            gvOrder.RowCellClick += gvOrder_RowCellClick;
            gvOrder.ValidateRow += gvOrder_ValidateRow;
            gvOrder.InvalidRowException += gvOrder_InvalidRowException;
            gvOrderLines.RowCellClick += gvOrderLines_RowCellClick;
            gvOrderLines.CustomDrawCell += gvOrderLines_CustomDrawCell;
            
            gvOrderLines.CustomColumnDisplayText += gvOrderLines_CustomColumnDisplayText;
            gvOrderLines.RowCellStyle += gvOrderLines_RowCellStyle;
            gvOrderLines.ValidateRow += gvOrderLines_ValidateRow;
            gvOrderLines.InvalidRowException += gvOrderLines_InvalidRowException;

            gvOrderLines.Columns["ColourId"].ColumnEdit = Utility.GetGLESablon(Data.DB.Colour, "Name", "ColourId");
            gvOrderLines.Columns["BallSizeId"].ColumnEdit = Utility.GetGLESablon(Data.DB.BallSize, "Name", "BallSizeId");
            gvOrderLines.SetCaptions("ColourId:Colour", "BallSizeId:Ball Size");

            gvOrder.BestFitColumns();
            gvOrderLines.BestFitColumns();
             
        }
         
        private void AddProductManual_Click(object sender, EventArgs e)
        {
            AddProduct adder = new AddProduct();
            adder.ShowDialog();

            Orders_BarcodeRead(adder.ProductId);
        }

        private void Orders_BarcodeRead(int ProductId)
        {
            if (Data.DB.Product.FindByProductId(ProductId) != null)
            {
                int OrderId = (int)gvOrder.GetFocusedRowCellValue("OrderId");

                if (Data.DB.OrderLines.Select(string.Format("OrderId={0} and ProductId={1}", OrderId, ProductId)).Length > 0)
                    Console.Beep();
                else
                {
                    foreach (ErsurDB.OrderLinesRow dr in Data.DB.OrderLines.Select("OrderId=" + OrderId.ToString()))
                        Data.DB.OrderLines.RemoveOrderLinesRow(dr);

                    DataSet dsData = Data.ExecuteDataSet("InsOrderLines", OrderId, ProductId);
                    dsData.Tables[0].TableName = "OrderLines";
                    Data.DB.OrderLines.Merge(dsData.Tables[0]);
                    gvOrderLines.BestFitColumns();
                }
            }
        }

        private void SendMail_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            List<DataRow> drs = new List<DataRow>();
            foreach (int rowHandle in gvOrder.GetSelectedRows())
                drs.Add(gvOrder.GetDataRow(rowHandle));

            AppSession.MainForm.Info = Data.SendEmail(drs.ToArray());

            this.Cursor = Cursors.Default;
        }

        private void Sync_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            List<DataRow> drs = new List<DataRow>();
            foreach (int rowHandle in gvOrder.GetSelectedRows())
                drs.Add(gvOrder.GetDataRow(rowHandle));

            AppSession.MainForm.Info = Data.Sync(drs.ToArray());

            this.Cursor = Cursors.Default;
        }

        private void MarkAsSent_Click(object sender, EventArgs e)
        {
            foreach (int rowHandle in gvOrder.GetSelectedRows())
            {
                DataRow dr = gvOrder.GetDataRow(rowHandle);
                if (dr["eMailDate"] == DBNull.Value)
                    dr["eMailDate"] = DateTime.Now;
            }
            Data.Save();
        }

        private void PrintOrderArticles_Click(object sender, EventArgs e)
        {
            if (gvOrderLines.DataRowCount < 1)
                return;

            string list = string.Empty;

            for (int i = 0; i < gvOrderLines.DataRowCount; i++)
                list += gvOrderLines.GetDataRow(i)["ProductId"] + ",";

            list = list.Substring(0, list.Length - 1);

            DataSet dsReport = Data.ExecuteDataSet("GetProductReport", list);

            ProductReportSettings el = new ProductReportSettings();
            el.DisableManualOrdering();
            el.ShowDialog();

            int counter = Convert.ToInt32(el.emptyCount.Value);
            int copyCount = Convert.ToInt32(el.copyCount.Value);

            ProductReport pr = new ProductReport(dsReport, counter, copyCount);

            pr.ShowPreview();
        }

        private void splitter_SizeChanged(object sender, EventArgs e)
        {
            splitter.SplitterPosition = (splitter.Horizontal ? splitter.Width : splitter.Height) / 2 + 40;

        }

        private void PrintOrder_Click(object sender, EventArgs e)
        {
            int[] selectedRows = gvOrder.GetSelectedRows();

            if (selectedRows.Length == 0)
                return;

            int orderId = (int)gvOrder.GetRowCellValue(selectedRows[0], "OrderId");
            DataSet dsReport = Data.ExecuteDataSet("GetOrderReport", orderId, Settings.TerminalNo, Settings.FairNo);

            OrderReport r1 = new OrderReport(dsReport.Copy());
            r1.CreateDocument();

            //OrderReport r2 = new OrderReport(dsReport.Copy(), true);
            //r2.CreateDocument();
            //r1.Pages.AddRange(r2.Pages);

            for (int i = 1; i < selectedRows.Length; i++)
            {
                int tempOrderId = (int)gvOrder.GetRowCellValue(selectedRows[i], "OrderId");
                DataSet dsTemp = Data.ExecuteDataSet("GetOrderReport", tempOrderId, Settings.TerminalNo, Settings.FairNo);

                OrderReport r2 = new OrderReport(dsTemp.Copy());
                r2.CreateDocument();
                r1.Pages.AddRange(r2.Pages);

                //r2 = new OrderReport(dsTemp.Copy(), true);
                //r2.CreateDocument();
                //r1.Pages.AddRange(r2.Pages);
            }

            r1.PrintingSystem.ContinuousPageNumbering = false;

            ReportPrintTool printTool = new ReportPrintTool(r1);
            printTool.ShowPreviewDialog();
        }

        private void gvOrderLines_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            try
            {
                if (e.Column.Name == "Remove" && e.RowHandle > -1)
                {
                    e.DisplayText = "X";
                    e.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Underline);
                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrder_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Cancelled")
            {
                object currentVal = e.CellValue;
                if (currentVal == null || currentVal == DBNull.Value || (bool)currentVal == true)
                    gvOrder.SetRowCellValue(e.RowHandle, "Cancelled", false);
                else
                    gvOrder.SetRowCellValue(e.RowHandle, "Cancelled", true);

                Data.Save();
            }
        }

        private void gvOrder_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            try
            {
                string fieldName = e.Column.FieldName;
                if (fieldName == "SyncDate")
                {
                    if (e.CellValue != null && e.CellValue != DBNull.Value)
                        e.Appearance.BackColor = Color.Gold;
                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrder_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                if (e.RowHandle > -1)
                {
                    if ((bool)gvOrder.GetRowCellValue(e.RowHandle, "Cancelled"))
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                    }
                    else
                    {
                        if (e.RowHandle == gvOrder.FocusedRowHandle)
                            e.Appearance.BackColor = e.Appearance.BackColor = Color.YellowGreen;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? gvOrder.Appearance.EvenRow : gvOrder.Appearance.OddRow);
                    }
                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrderLines_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            try
            {
                string fieldName = e.Column.FieldName;
                if ("ColourId BallSizeId Notes".Contains(fieldName))
                    e.Appearance.BackColor = Color.LemonChiffon;
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrderLines_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.Name == "Remove")
            {
                if (XtraMessageBox.Show("Are you sure to remove the product?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    int OrderId = (int)gvOrder.GetFocusedRowCellValue("OrderId");
                    int ProductId = (int)gvOrderLines.GetRowCellValue(e.RowHandle, "ProductId");

                    foreach (DataRow dr in Data.DB.OrderLines.Select("OrderId=" + OrderId.ToString()))
                        Data.DB.OrderLines.Rows.Remove(dr);

                    DataSet dsData = Data.ExecuteDataSet("DelOrderLines", OrderId, ProductId);
                    dsData.Tables[0].TableName = "OrderLines";
                    Data.DB.Merge(dsData);
                    gvOrderLines.BestFitColumns();
                }
            }
            else if (e.Column.FieldName == "Cancelled")
            {
                object currentVal = e.CellValue;
                if (currentVal == null || currentVal == DBNull.Value || (bool)currentVal == true)
                    gvOrderLines.SetRowCellValue(e.RowHandle, "Cancelled", false);
                else
                    gvOrderLines.SetRowCellValue(e.RowHandle, "Cancelled", true);

                Data.Save();
            }
        }

        private void gvOrderLines_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
        {
            if (e.ListSourceRowIndex < 0)
                return;

            if (Data.ProductDetails.Contains(e.Column.FieldName))
            {
                object productId = gvOrderLines.GetRowCellValue(e.ListSourceRowIndex, "ProductId");
                if (productId == null || productId == DBNull.Value)
                    return;

                int id = -1;
                if (int.TryParse(productId.ToString(), out id))
                {
                    DataRow pr = Data.DB.Product.Select("ProductId = " + id)[0];

                    if (pr != null)
                        e.DisplayText = pr[e.Column.FieldName].ToString();
                }
            }
        }   

        private void gvOrder_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
        }

        private void gvOrder_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            DialogResult result = XtraMessageBox.Show("Changes will be submitted.", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                int cellOrderId = (int)gvOrder.GetRowCellValue(e.RowHandle, "OrderId");
                Data.DB.Order.Select("OrderId=" + cellOrderId)[0]["EditDate"] = DateTime.Now;
                 
                gvOrder.EndEditing();
                 
                Data.Save();
            }
            else
            {
                e.Valid = false;
            }
        } 
         
        private void gvOrderLines_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
        }     

        private void gvOrderLines_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            DialogResult result = XtraMessageBox.Show("Changes will be submitted.", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                int cellOrderId = (int)gvOrderLines.GetRowCellValue(e.RowHandle, "OrderId");
                Data.DB.Order.Select("OrderId=" + cellOrderId)[0]["EditDate"] = DateTime.Now;

                gvOrderLines.EndEditing();

                Data.Save();
            }
            else
            {
                e.Valid = false;                
            }
        }      
    }
}